
package connection;

import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;

/**
 * @version 1.0
 * @author André Pinto de Souza
 */
public class YahooQuotesConnector {

    private final StringBuffer m_Url = new StringBuffer("http://download.finance.yahoo.com/d/quotes.csv?s=.SA&f=sl1d1t1c1ohgv&e=.csv");
    private String m_Code = null;
    private String m_Response = null;

    public YahooQuotesConnector(String p_Code)
    {
        m_Code = p_Code;
        run();
    }

    public String getResponse()
    {
        return m_Response;
    }

    private void run() {
        InputStream is = null;
        HttpConnection conn = null;

        try {
            String v_Url = m_Url.insert(m_Url.toString().indexOf("=") + 1, m_Code).toString();
            conn = (HttpConnection) Connector.open(v_Url, Connector.READ_WRITE);
        } catch (Exception ex) {
            System.out.println(ex);
            ex.printStackTrace();
            Alert alert = new Alert("Invalid Address", "Invalid Address",  null, AlertType.ERROR);
            alert.setTimeout(Alert.FOREVER);
            return;
        }

        try {
            // Fetch the required page, reading up
            // to a maximum of 128 bytes
            if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
                is = conn.openInputStream();
                final int MAX_LENGTH = 128;
                byte[] buf = new byte[MAX_LENGTH];
                int total = 0;
                while (total < MAX_LENGTH) {
                    int count = is.read(buf, total, MAX_LENGTH - total);
                    if (count < 0) {
                        break;
                    }
                    total += count;
                }
                is.close();
                String reply = new String(buf, 0, total);
                m_Response = reply;
            } else {
                m_Response = conn.getResponseCode() + "";
            }
            conn.close();
        } catch (IOException ex) {
            System.out.println(ex);
            ex.printStackTrace();
            Alert alert = new Alert("I/O Error",
                    "An error occurred while communicating with the server.",
                    null, AlertType.ERROR);
            alert.setTimeout(Alert.FOREVER);
            return;
        } finally {
            // Close opened streams
            try {
                if (is != null) {
                    is.close();
                    is = null;
                }
            } catch (IOException ex1) {
            }
            try {
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (IOException ex1) {
            }
        }

    }
}
